<template>
  <div class="login_wrap" v-if="isPC()">
    <div class="login_card_wrap">
      <div class="card_n_box">
        <div class="left_box">
          <div class="title_box">
            <span class="title_text">实验室药品仪器管理中心</span>
          </div>
          <div class="login_form_box">
            <el-form
              :label-position="'top'"
              ref="loginFormRef"
              :rules="loginFormRules"
              label-width="auto"
              :model="loginForm"
              style="max-width: 600px"
              @keyup.enter="loginBtnClick(loginFormRef)"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="loginForm.password" />
              </el-form-item>
              <div class="sliding_block_v_box">
                <Vcode :show="isShow" @success="onSuccess" @close="onClose" />
                <!-- <el-button v-if="!isSuccessSlidingBlockV" style="width: 100%" @click="onShow" type="primary" size="large" plain>
                  <i class="iconfont icon-clickToVerify" style="position: relative; top: -0.8px; margin-right: 6px"></i>
                  <span>点击进行验证</span>
                </el-button>
                <el-button v-else style="width: 100%" type="success" size="large" plain>
                  <i class="iconfont icon-sliderVerificationSucceeded" style="margin-right: 6px"></i>
                  <span>验证通过</span>
                </el-button> -->
              </div>
              <el-form-item>
                <el-button
                  style="width: 100%; margin-top: 40px; background-color: #2a8ff4"
                  size="large"
                  type="primary"
                  @click="loginBtnClick(loginFormRef)"
                >
                  <span style="padding-left: 10px; letter-spacing: 8px">登录</span>
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="right_box">
          <img class="fx_img" src="./image/fx.png" alt="" />
          <span class="right_title">让管理更方便</span>
        </div>
      </div>
    </div>

    <!-- 备案信息 -->
    <div class="archival_info_box">
      <span class="archival_text" @click="archivalClick">浙ICP备16024894号</span>
    </div>
  </div>
  <LoginMobile v-else></LoginMobile>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onBeforeUnmount } from "vue";
export default defineComponent({
  name: "Login"
});
</script>
<script setup lang="ts">
import LoginMobile from "./loginMobile/index.vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useAuthStore } from "@/stores/modules/auth";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import type { ElForm } from "element-plus";
import dayjs from "dayjs";
import Vcode from "vue3-puzzle-vcode";
import { ElMessage } from "element-plus";
import { isPC } from "@/utils/sys";

const userStore = useUserStore();
const authStore = useAuthStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  password: ""
});

// router
const router = useRouter();
// 是否通过滑块验证的标识
const isSuccessSlidingBlockV = ref(false);

const isShow = ref(false);

// const onShow = () => {
//   isShow.value = true;
// };

const onClose = () => {
  isShow.value = false;
};

const onSuccess = () => {
  onClose(); // 验证成功，手动关闭模态框
  isSuccessSlidingBlockV.value = true;
  login();
};

// 登录点击事件
const loginBtnClick = (formEl: FormInstance | undefined) => {
  console.log("登录点击");

  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;

    isShow.value = true;
    try {
    } finally {
    }
  });
};

// login
const login = async () => {
  loading.value = true;
  // 判断是否通过人机验证
  // if (isSuccessSlidingBlockV.value) {
  // 1.执行登录接口
  await loginApi({
    account: loginForm.username,
    psw: loginForm.password
  })
    .then(async res => {
      console.log(res, "res");

      if (res.result == "success") {
        console.log("登录res", res);

        // 存储token
        userStore.setToken(res.data.accessToken);

        console.log(userStore.userInfo);

        // 存储用户信息
        userStore.userInfo.name = res.data.name;
        userStore.userInfo.id = res.data.id;
        userStore.userInfo.account = res.data.account;
        userStore.userInfo.isManager = res.data.isManager;

        // console.log(setLocalData);
        let setLocalData = {
          token: res.data.accessToken,
          userInfo: {
            name: res.data.name,
            id: res.data.id,
            account: res.data.account,
            isManager: res.data.isManager,
            sIsM: res.data.permission.isManager,
            sIsU: res.data.permission.isUser
          }
        };

        let permissionData = res.data.permission;

        console.log("用户信息1", setLocalData);

        localStorage.setItem("geeker-user", JSON.stringify(setLocalData));
        localStorage.setItem("permission", JSON.stringify(permissionData));

        // getAuthMenuListApi();

        authStore.getAuthMenuList();

        // 设置存token的时间
        let setTokenTime = dayjs().valueOf();
        console.log("存Token时间", setTokenTime);
        localStorage.setItem("setTokenTime", JSON.stringify(setTokenTime));

        // 2.添加动态路由
        await initDynamicRouter();

        // 3.清空 tabs、keepAlive 数据
        tabsStore.setTabs([]);
        keepAliveStore.setKeepAliveName([]);

        // 4.跳转到首页
        // setTimeout(() => {
        console.log("当前路由表", authStore.authMenuList);

        router.push(HOME_URL);
        ElNotification({
          title: getTimeState(),
          message: "欢迎登录!",
          type: "success",
          duration: 3000
        });
        // }, 2000);
      } else {
        ElMessage.error(res.msg);
      }
    })
    .finally(() => {
      loading.value = false;
    });
  // } else {
  //   ElMessage.error("请先进行验证");
  // }
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  // document.onkeydown = (e: KeyboardEvent) => {
  //   if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
  //     if (loading.value) return;
  //     login(loginFormRef.value);
  //   }
  // };
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});

// 登录表单校验规则
const loginFormRules = ref({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur"
    }
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur"
    }
  ]
});

// 备案点击事件
const archivalClick = () => {
  window.open("https://beian.miit.gov.cn");
};
</script>

<style lang="scss" scoped>
.login_wrap {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: url("./image/bg.png") no-repeat;
  background-size: 100% 100%;
  .login_card_wrap {
    position: absolute;
    top: 50%;
    left: 51%;

    // border: 1px solid red;
    width: 960px;
    height: 600px;
    background: url("./image/card_bg_mask.png") no-repeat;
    background-size: 100% 100%;
    transform: translate(-50%, -50%);
    .card_n_box {
      position: relative;
      top: 3%;
      left: 1.2%;
      display: flex;
      flex-direction: row;

      // border: 1px solid red;
      width: 91.4%;
      height: 87%;
      overflow: hidden;
      border-radius: 14px;
      .left_box {
        width: 460px;
        height: 100%;

        // border: 1px solid red;

        background-color: white;
        .title_box {
          width: 100%;
          height: 160px;
          line-height: 160px;
          text-align: center;

          // height: 20%;
          // line-height: 20%;
          .title_text {
            font-family: ZaoZiGongFangJianHei;
            font-size: 28px;
            letter-spacing: 6px;

            // color: white;
          }
        }
        .login_form_box {
          // border: 1px solid red;
          height: 69%;
          padding: 30px 70px;
          .sliding_block_v_box {
            padding: 10px 0 0;
            margin-top: 14px;
          }
        }
      }
      .right_box {
        // border: 1px solid red;
        position: relative;
        flex: 1;
        .right_title {
          position: absolute;
          top: 38%;
          display: inline-block;
          width: 100%;
          font-family: ZQKLKT;
          font-size: 32px;
          color: white;
          text-align: center;
          letter-spacing: 10px;
        }
        .fx_img {
          // width: 800px;
          // border: 1px solid red;
          position: absolute;
          right: -195px;
          bottom: -78px;
          transform: scale(0.56);
        }
        .mx_box {
          display: flex;
          flex-flow: row wrap;
          width: 100%;
          height: 400px;
          border: 1px solid red;
          img {
            width: 120px;
            height: 120px;
          }
        }
      }
    }
  }
}

// input
:deep(.el-input) {
  .el-input__wrapper {
    .el-input__inner {
      letter-spacing: 1px;
    }
  }
}

/* 备案信息 */
.archival_info_box {
  position: fixed;
  bottom: 20px;
  width: 100%;
  text-align: center;

  // border: 1px solid red;
  .archival_text {
    font-size: 14px;
    color: rgb(94 93 93);
    letter-spacing: 1px;
    cursor: pointer;
  }
  .archival_text:hover {
    color: blue;
  }
}
</style>
